package com.ssm.controller;


import java.util.HashMap;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ssm.pojo.Result;
import com.ssm.pojo.user.User;
import com.ssm.service.UserService;



@Controller
public class UserController {
	  @Autowired
	  UserService userService;
	  
	  // 用户登录
	  @RequestMapping(value="/userLogin")
	  public String login() {
			return "user/userLogin";
	  }
	  
	  // 找回密码
	  @RequestMapping(value="/userRetrievePassword")
	  public String userRetrievePassword() {
				return "user/userRetrievePassword";
	  }
	  
	  // 用户注册
	  @RequestMapping(value="/userAdd")
	  public String userAdd() {
				return "user/userAdd";
	  }
	  
	  // 注册协议
	  @RequestMapping(value="/registrationAgreement")
	  public String registrationAgreement() {
				return "user/registrationAgreement";
	  }
	  
	  // 修改密码
	  @RequestMapping(value="/updatePassword")
	  public String updatePassword() {
				return "user/updatePassword";
	  }
	  
	  // 用户登录
      @RequestMapping(value="/userLoginData",method = RequestMethod.POST)
	  @ResponseBody
	  public Result login(HttpSession session,User user) {
			return userService.login(session, user);
	  }
      
      // 修改用户
      @RequestMapping(value="/updateUser",method = RequestMethod.POST)
	  @ResponseBody
	  public Result update(HttpSession session,User user) {
			return userService.updateUser(session,user);
	  }
      
      // 退出登录
      @RequestMapping("/userLogout")
      public String logout(HttpSession session){
          //清除session
          session.invalidate();
          //重定向到登录页面的跳转方法
          return "redirect:userLogin";
      }
	  
	  // 添加用户验证，新增邮箱验证
	  @RequestMapping(value="/userValidate",method = RequestMethod.POST)
	  @ResponseBody
	  public Result Validate(HttpSession session,User user,Integer explainCode) {
		  Result result = new Result();
		  String userNameTemp = user.getUserName();
		  if(userNameTemp == null) {
		        String userName = (String) session.getAttribute("userName");
		        userNameTemp = userName;
		        if(userNameTemp != null) {
		        	user.setUserName(userName);
		        }else {
		        	result.setErrorCode(1);
		        	result.setErrorMsg("用户名获取失败");
		        	return result;
		        }
		  }
		  String explain = null;
		  if(explainCode.equals(1)) {
			  explain = "欢迎注册ssmShop";
		  }else {
			  explain = "此邮箱将作为您ssmShop的邮箱";
		  }
		  return sendVerfyCode(session,user,explain,"verifyCode");
	  }
	  
	  // 修改密码验证，修改邮箱验证
	  @RequestMapping(value="/autoUserValidate",method = RequestMethod.POST)
	  @ResponseBody
	  public Result autoValidate(HttpSession session,User user,Integer explainCode) {
		  String explain = null;
		  if(explainCode.equals(1)) {
			  explain = "您正在修改ssmShop的密码";
		  }else {
			  explain = "您正在修改ssmShop的邮箱";
		  }
		  Result result = new Result();
		  User userInfo = new User();
		  if (user.getUserName().isEmpty() && session.getAttributeNames().hasMoreElements()) {
			  String userName = (String) session.getAttribute("userName");
			  String email = (String) session.getAttribute("email");
			  if(userName.isEmpty() || email.isEmpty()) {
				   result.setErrorCode(1);
				   result.setErrorMsg("查询用户信息失败");
				   return result;
			  }
			  userInfo.setUserName(userName);userInfo.setEmail(email);
		  }else {
			  user.setEmail(user.getUserName());
			  User userGet = userService.get(user);
			  userInfo = userGet;
			  if(userGet == null) {
				   result.setErrorCode(1);
				   result.setErrorMsg("用户未注册");
				   return result;
			  }
		  }
		  return sendVerfyCode(session,userInfo,explain,"autoVerifyCode");
	  }
	
	  // 添加用户
	  @RequestMapping(value="/userAdd",method = RequestMethod.POST)
	  @ResponseBody
	  public Result add(HttpSession session,User user) {
		 Result result = checkVerfyCode(session,user,"verifyCode");
		 if (result.getErrorCode().equals(0)) {
			 return userService.add(session,user);
		}else {
			return result;
		}
	  }
	  
	 // 修改密码
	  @RequestMapping(value="/updatePassword",method = RequestMethod.POST)
	  @ResponseBody
	  public Result updatePassword(HttpSession session,User user) {
		 Result result = checkVerfyCode(session,user,"autoVerifyCode");
		 if (result.getErrorCode().equals(0)) {
			  if (user.getUserName().isEmpty()) {
				  int userId = (int) session.getAttribute("userId");
				  if(String.valueOf(userId).isEmpty()) {
					   result.setErrorCode(1);
					   result.setErrorMsg("查询用户id失败");
					   return result;
				  }
				  user.setUserId(userId);
			  }else {
				  user.setEmail(user.getUserName());
				  User userGet = userService.get(user);
				  User userTemp = userGet;
				  if(userTemp == null) {
					   result.setErrorCode(1);
					   result.setErrorMsg("查询用户信息失败");
					   return result;
				  }
				  user.setUserId(userGet.getUserId());
			  }
			  
			 return userService.updateUserPassword(session,user);
		}else {
			return result;
		}
	  }
	  
	  // 修改邮箱
	  @RequestMapping(value="/updateEmail",method = RequestMethod.POST)
	  @ResponseBody
	  public Result updateEmail(HttpSession session,User user,int newVerifyCode) {
		 Result result = checkVerfyCode(session,user,"autoVerifyCode");
		 if (result.getErrorCode().equals(0)) {
			 user.setVerifyCode(newVerifyCode);
			 result = checkVerfyCode(session,user,"verifyCode");
			 if(result.getErrorCode().equals(0)) {
				  int userId = (int) session.getAttribute("userId");
				  if(String.valueOf(userId).isEmpty()) {
					   result.setErrorCode(1);
					   result.setErrorMsg("查询用户id失败");
					   return result;
				  }
				  user.setUserId(userId);
				  return userService.updateUserEmail(session,user);
			 }
		}
		return result;
	  }
	
	  // 发送验证码
	  private Result sendVerfyCode(HttpSession session,User user,String explain,String code) {
		   Integer verifyCode = userService.sendCode(user,explain);
		   HashMap<String, String> map = new HashMap<String, String>();
		   map.put("verifyCode", String.valueOf(verifyCode));
		   map.put("createTime", String.valueOf(System.currentTimeMillis()));
		   // 将认证码存入SESSION
		   session.setAttribute(code, map);
		   Result result = new Result();
		   if(verifyCode.toString().length() == 6) {
			   result.setErrorCode(0);
			   result.setErrorMsg("发送验证码成功");
		   }else {
			   result.setErrorCode(1);
			   result.setErrorMsg("发送验证码失败");
		   }
		return result;
	  }
	  
	  // 验证码检查
	  private Result checkVerfyCode(HttpSession session,User user,String code) {
		@SuppressWarnings("unchecked")
		HashMap<String, String> map = (HashMap<String, String>) session.getAttribute(code);
			HashMap<String, String> tempMap = map;
			Result result = new Result();
			if (tempMap==null || !Integer.valueOf(map.get("verifyCode")).equals(user.getVerifyCode())) {
				   result.setErrorCode(1);
				   result.setErrorMsg("验证码错误");
				   return result;
			 }
			 if((System.currentTimeMillis() - Long.valueOf(map.get("createTime"))) > 1000 * 60 * 10){
				  result.setErrorCode(1);
				  result.setErrorMsg("验证码过期");
				  return result;
			 }
			 result.setErrorCode(0);
			 result.setErrorMsg("验证成功");
			 return result;
	  }
}
